﻿using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevTeam;
using Fatura;
using System;
using System.Data;
using System.Drawing;

namespace Fatura
{


    public partial class Sablon : XImportWizard
    {
        public Sablon()
        {
            InitializeComponent();
            pe = new ParseExcel();
        }

        ParseExcel pe;
        private void Form1_Load(object sender, EventArgs e)
        {            
            this.FileDone += Form1_FileDone;
            this.ProcessDone += Form1_ProcessDone;
            this.ProcessStart += Form1_ProcessStart;

            gvAction.Init("FT_GetSablon", 0, 0);

            dtMusteri = ExecuteDataTable("FT_GetCustomer");
            RepositoryItemGridLookUpEdit riMusteri = RepositoryManager.GetGLESablon(dtMusteri, "Name", "CustomerId");
            dtCaptions = ExecuteDataTable("FT_GetTableColumns", "FT_InvoiceHeader");

            gleSirket.Edit.Assign(RepositoryManager.Get("SirketId"));
            gleMusteri.Edit.Assign(riMusteri);

            RepositoryItemGridLookUpEdit riCaptions = RepositoryManager.GetGLESablon(dtCaptions, "Name", "Name");

            gvAction.Columns["ActionId"].ColumnEdit = pe.riAction;
            gvAction.Columns["DirectionId"].ColumnEdit = pe.riDirection;
            gvAction.Columns["StopConditialId"].ColumnEdit = pe.riEmpty;
            gvAction.Columns["DBCaption"].ColumnEdit = riCaptions;

            gvAction.SetCaptions("SablonId:#", "SablonLinesId:No");
            gvAction.MakeColumnInvisible("SablonId", "SablonLinesId", "DBCaption2");

            GridManager gm = GridManager.GetManager(gvMaster);
            gm.GridMenu.AddMenu("Fatura Satırları olarak ekle", AddInvoiceLine);
            gm.GridMenu.AddMenu("Şablona Ekle (Bul)", AddInvoice);
            gm.GridMenu.AddMenu("Şablona Ekle (Yönlü)", AddInvoice2);

            //gvAction.MakeReadOnly();
            gvAction.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            btnSave.ItemClick += btnSave_ItemClick;

            gleMusteri.EditValueChanged += gleMusteri_EditValueChanged;
            gleSirket.EditValueChanged+=gleSirket_EditValueChanged;

            gvAction.BestFitColumns();
        }

        private void AddInvoice2(object sender, EventArgs e)
        {
            AddToSablon(2);
        }

        private void AddInvoice(object sender, EventArgs e)
        {
            AddToSablon(1);
        }

        private void AddToSablon(int Action)
        {
            DataTable dt = gvAction.DataTable();
            foreach (GridCell gc in gvMaster.GetSelectedCells())
            {
                string ExcelCaption = gvMaster.GetRowCellValue(gc.RowHandle, gc.Column).ToStr();
                if (ExcelCaption != "")
                {
                    DataRow drSablon = dt.NewRow();
                    drSablon["ActionId"] = Action;
                    drSablon["ExcelCaption"] = ExcelCaption;
                    if (dtCaptions.Select("Name='" + ExcelCaption.Replace(" ", "") + "'").Length > 0)
                        drSablon["DBCaption"] = ExcelCaption.Replace(" ","");
                    dt.Rows.Add(drSablon);
                }
            }
        }

        private void AddInvoiceLine(object sender, EventArgs e)
        {
            DataRow dr = ((DataRowView)gvMaster.GetRow(gvMaster.FocusedRowHandle)).Row;
            foreach (object item in dr.ItemArray)
            {
                string value = item.ToStr();
                if (value != "")
                {
                    DataTable dt = gvAction.DataTable();
                    DataRow[] drSelect = dt.Select("ExcelCaption='" + value + "'");

                    if (drSelect.Length == 0)
                    {
                        DataRow drSablon = dt.NewRow();
                        drSablon["ActionId"] = 3;
                        drSablon["ExcelCaption"] = value;
                        if (dtCaptions.Select("Name='" + value.Replace(" ", "") + "'").Length > 0)
                            drSablon["DBCaption"] = value.Replace(" ", "");
                        dt.Rows.Add(drSablon);
                    }
                }
            }
        }

        DataTable dtMusteri, dtCaptions;
        void gleSirket_EditValueChanged(object sender, EventArgs e)
        {
            gleMusteri.Enabled = gleSirket.EditValue.ToInt() > 0;
            gleMusteri.EditValue = null;

            DataTable dtSirket = (DataTable)((RepositoryItemGridLookUpEdit)gleSirket.Edit).DataSource;
            string Sirket = dtSirket.Select("SirketId=" + gleSirket.EditValue)[0]["Name"].ToStr();

            dtMusteri.DefaultView.RowFilter = "Sirket = '" + Sirket + "'";
            gleMusteri.Edit.Assign(GetCustomGLE(dtMusteri, "Name", "CustomerId"));
            
        }

        void gleMusteri_EditValueChanged(object sender, EventArgs e)
        {
            bbiOnizle.Enabled = btnSave.Enabled = btnProcessFile.Enabled = gleMusteri.EditValue.ToInt() > 0;
            gvAction.RefreshDataSource("FT_GetSablon", gleSirket.EditValue, gleMusteri.EditValue);
            gvAction.BestFitColumns();

        }

        void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvAction.EndEditing();

            DataTable dtSablon = gvAction.DataTable();

            if (gleSirket.EditValue.ToInt()==0)
            {
                ShowErrorMessage("Şirket boş olamaz!");
                return;
            }
            
            if (dtSablon.Rows.Count == 0)
            {
                ShowErrorMessage("Şablon kurallarını doldurun!");
                return;
            }

            DataRow[] drExcYOnBelirle = dtSablon.Select("ActionId = 2 and (StopConditialId is null or DirectionId is null)");
            if (drExcYOnBelirle.Length > 0)
            {
                ShowErrorMessage("Yön belirtin!");
                return;
            }

            DataRow[] drExcNullCaption = dtSablon.Select("ActionId <> 4 and Isnull(DBCaption,'') = ''");
            if (drExcNullCaption.Length > 0)
            {
                ShowErrorMessage("DBCaption alanını doldurun!");
                return;
            }
            string xml = gvAction.Serialize();
            ExecuteNonQuery("FT_SaveSablon", gleSirket.EditValue, gleMusteri.EditValue, xml, WhoAmI);

            gvAction.RefreshDataSource("FT_GetSablon", gleSirket.EditValue, gleMusteri.EditValue); 
        }

        void Form1_ProcessStart()
        {
            ds = new DataSet();
        }

        void Form1_ProcessDone()
        {
            DataTable dt = ds.Tables[0];
            gvMaster.Init(dt);
        }

        DataSet ds;
        void Form1_FileDone(DataSet Data, string FileName)
        {
            ds = Data;
        }

        private void bbiOnizle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvAction.EndEditing();

            DataTable dtSablon = gvAction.DataTable();
            if (dtSablon.Rows.Count == 0)
            {
                ShowErrorMessage("Şablon tanımlamadan dosyadan okuyamazsınız!");
                return;
            }

            DataTable dtInvoiceLines = pe.GetInvoiceLines(ds.Tables[0], "Total  Value");
            foreach (DataColumn dc in dtInvoiceLines.Columns)
            {
                string ExcelCaption = dc.ColumnName;
                DataRow[] drDBCaption = dtSablon.Select("ActionId in (3) and ExcelCaption = '" + ExcelCaption + "'");

                if (drDBCaption.Length > 0)
                    dc.ColumnName = drDBCaption[0]["DBCaption"].ToStr();
            }

            gvDetail.Init(dtInvoiceLines);
            gvDetail.BestFitColumns();

            foreach (DataRow dr in dtSablon.Select("ActionId in (1,2)"))
            {
                int Action = dr["ActionId"].ToInt();
                int Yon = dr["DirectionId"].ToInt();
                int Dur = dr["StopConditialId"].ToInt();
                string ExcelCaption = dr["ExcelCaption"].ToStr();
                string DBCaption = dr["DBCaption"].ToStr();

                string Value = "";
                if (Action == 1)
                    Value = pe.GetValue(ds.Tables[0], ExcelCaption, ParseExcel.Direction.Down);
                else if (Action == 2)
                {
                    bool stop = Dur == 2;
                    Value = pe.GetValue(ds.Tables[0], ExcelCaption, (ParseExcel.Direction)Yon, stop);
                }

                if (Value != "")
                {
                    if (DBCaption.Contains("Date"))
                        Value = DateTime.FromOADate(double.Parse(Value)).ToString("dd.MM.yyyy");

                    meSonuc.Text += DBCaption + " : " + Value + Environment.NewLine;
                }
            }

            string DovizCinsi = ds.Tables[ds.Tables.Count - 1].Rows[0]["DovizCinsi"].ToStr();
            meSonuc.Text += "DovizCinsi : " + DovizCinsi + Environment.NewLine;

            foreach (DataRow dr in dtSablon.Select("ActionId=4"))
            {
                string ExcelCaption = dr["ExcelCaption"].ToStr();
                bool ReadRightCell = dr["ReadRightCell"].ToBool();

                DataTable dtSubTotals = pe.GetSubTotal(ds.Tables[0], ExcelCaption, ReadRightCell);
                int SubTotalIndex = 1;
                foreach (DataRow drSubTotal in dtSubTotals.Rows)
                {
                    string TotalcolumnName = (ExcelCaption.ToLower() == "total  value" ? "SubTotal" : "TotalQty") + SubTotalIndex.ToStr();
                    string DesccolumnName = (ExcelCaption.ToLower() == "total  value" ? "SubTotal" : "TotalQty") + SubTotalIndex.ToStr() + "Desc";

                    meSonuc.Text += TotalcolumnName + " : " + drSubTotal["Total"] + Environment.NewLine;
                    meSonuc.Text += DesccolumnName + " : " + drSubTotal["TotalDesc"] + Environment.NewLine;
                    SubTotalIndex++;
                }
            }

        }
    }
}
